do (angular) ->
  extend = angular.extend

  angular.module 'tini'

  .factory 'index', ($rootScope, $filter, req) ->
    index = null

    (cb) ->
      (index && cb? index) || req.index (data) ->
        return (cb? index) if index

        # 按时间新到旧排序文章
        posts = data.posts.sort (a, b) ->
          b.date - a.date

        # 建立文章索引
        indexes = {}
        categories = {}
        tags = {}
        archives = {}
        for post, i in posts
          post.index = i
          indexes[post.id = post.path.substr 0, post.path.indexOf '.'] = post

          if post.categories
            for category in post.categories
              if categories[category]
                categories[category].push post
              else
                categories[category] = [post]

          if post.tags
            for tag in post.tags
              if tags[tag]
                tags[tag].push post
              else
                tags[tag] = [post]

          date = $filter('date') post.date, 'yyyy-MM'
          if archives[date]
            archives[date].push post
          else
            archives[date] = [post]

        # 重新排序 tag
        tagsSorted = []
        for tag, posts of tags
          tagsSorted.push
            name: tag
            posts: posts
            count: posts.length

        tagsSorted.sort (a, b) ->
          b.count - a.count

        # 根据标签名索引排序后的标签
        tagNamesSorted = []
        for tag in tagsSorted
          tagNamesSorted.push tag.name

        # 排序后的存档
        archivesSorted = []
        for archive, posts of archives
          archivesSorted.push
            name: archive
            posts: posts
            count: posts.length

        archivesSorted.sort (a, b) ->
          b.posts[0].date - a.posts[0].date

        extend data,
          indexes: indexes
          categories: categories
          tags: tags
          tagsSorted: tagsSorted
          tagNamesSorted: tagNamesSorted
          archives: archives
          archivesSorted: archivesSorted
        extend $rootScope, data
        $rootScope.all = data.posts

        index = data
        cb? data

  .factory 'title', ($rootScope, index) ->
    (title) ->
      index (data) ->
        titles = [data.config.title]
        titles.unshift(title) if title
        $rootScope.global.titles = titles
